package com.qf.filter;

import com.qf.entity.Employee;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request=(HttpServletRequest)req;
        HttpServletResponse response=(HttpServletResponse)resp;

        String requestURI = request.getRequestURI();//获取请求路径
        System.out.println("uri="+requestURI);
        if(requestURI.endsWith("login.jsp")|| requestURI.endsWith("login")||requestURI.endsWith(".css")||requestURI.contains("/img")||requestURI.contains("/main/")||requestURI.equals("/")){  //放行
            chain.doFilter(req,resp);
        }else{
            Employee emp= (Employee) request.getSession().getAttribute("employee");
            if(emp==null){
                response.setContentType("text/html;charset=utf-8");
                PrintWriter writer = response.getWriter();
                writer.print("<script>alert('请先登录');location.href='/login.jsp'</script>");
            }else{
                //放行
                chain.doFilter(request,resp);
            }
        }
    }

    @Override
    public void destroy() {

    }
}
